using System.CodeDom;
using System.Collections.Generic;
using System.ComponentModel;
using InterfaceWeaver.AopCore;
using Roslyn.Compilers.CSharp;
using System.Linq;

namespace InterfaceWeaver.CustomTool
{
    public class ImplementIEditableObjectAspectHandler : AspectHandlerBase<ImplementIEditableObjectAttribute>
    {
        public override AspectHandlingPriority GetHandlingPriorityOnProperty(AspectDispatcher context, AttributeSyntax attributeSyntax, PropertyDeclarationSyntax propertyDeclarationSyntax)
        {
            // Because it depends on INotifyPropertyChanged implementation...
            // TODO create one more life cycle step to register dependencies between aspect handlers
            return AspectHandlingPriority.AfterNormal;
        }

        public override bool HandleOnPropertyPreview(AspectDispatcher context, AttributeSyntax attributeSyntax)
        {
            return base.HandleOnPropertyPreview(context, attributeSyntax) && ((PropertyDeclarationSyntax)context.ParsedCodeContext.CurrentMemberSyntax).HasSetter();
        }

        /// <summary>
        /// Handles the on member.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="attributeSyntax">The attribute syntax.</param>
        /// <param name="propertyDeclarationSyntax"> </param>
        /// <param name="handlerStreams"> </param>
        /// <returns>
        /// True if the aspect is handled, false otherwise
        /// </returns>
        public override void HandleOnProperty(AspectDispatcher context, AttributeSyntax attributeSyntax, PropertyDeclarationSyntax propertyDeclarationSyntax, IDictionary<PropertyDeclarationSyntax, AspectTuple[]> handlerStreams)
        {
            var currentProperty = context.WeavedCodeContext.CurrentCodeMemberPropertyDeclaration.CurrentCodeMemberPropertyDeclaration;
            var currentType = context.WeavedCodeContext.CurrentTypeDeclaration;

            currentType.ImplementIEditableObject(
                currentType.IsInheriting<INotifyPropertyChanged>()
                || handlerStreams.SelectMany(item => item.Value).Any(aspectTuple => aspectTuple.Handler is ImplementINotifyPropertyChangedAspectHandler));

            // Recover IEditableObject methods
            var beginEditMethod = currentType.Members.OfType<CodeMemberMethod>().First(method => method.Name == "BeginEdit" && method.Parameters.Count == 0);
            var endEditMethod = currentType.Members.OfType<CodeMemberMethod>().First(method => method.Name == "EndEdit" && method.Parameters.Count == 0);
            var cancelEditMethod = currentType.Members.OfType<CodeMemberMethod>().First(method => method.Name == "CancelEdit" && method.Parameters.Count == 0);

            //var isEditingField = currentType.Members.OfType<CodeMemberField>().First(field => field.Name == "editionHasBegun");
            //var isEditingProperty = currentType.Members.OfType<CodeMemberProperty>().First(field => field.Name == "EditionHasBegun");
            
            var backupField = new CodeMemberField(currentProperty.Type, string.Format("{0}_IEditableObjectBackup", currentProperty.Name.ToCamelCase()));

            beginEditMethod.Statements.Insert(0, new CodeAssignStatement(
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), backupField.Name),
                new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), currentProperty.Name)));

            endEditMethod.Statements.Insert(0, new CodeAssignStatement(
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), backupField.Name),
                new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), currentProperty.Name)));

            cancelEditMethod.Statements.Insert(0, new CodeAssignStatement(
                new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), currentProperty.Name),
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), backupField.Name)));

            currentType.Members.Add(backupField);
        }
    }
}